// 首页index.js

// 工具函数 - 写在页面 JS 文件顶部或 utils 工具类中
function formatTime(postTimeStr) {
  // 处理 iOS/Safari 兼容性问题
  const postDate = new Date(postTimeStr.replace(' ', 'T'));
  const now = new Date();
  const diff = now - postDate;

  // 未来时间直接返回完整格式
  if (diff < 0) return formatFullDate(postDate);

  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  if (seconds < 60) return `${seconds}秒前`;
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  return formatFullDate(postDate);
}

function formatFullDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return year !== new Date().getFullYear() 
    ? `${year}年${month}月${day}日` 
    : `${month}月${day}日`;
}

Page({
  data: {
    // 初始数据
    postsList: [],       // 帖子列表
    page: 1,             // 当前页码
    showCommentPopup: false,
    currentPostId: null,  // 记录当前操作的帖子ID
    currentContent:null,
    postId:null,
    currentNickname:null,
    content:null,
    loading: false,      // 加载状态
    hasMore: true,       // 是否还有更多数据
    formatTime:0,
    searchText:null,
    uid:null
  },

  onLoad() {
    // 初始加载数据
    this.loadPosts();
  },

  onShow(){
    this.loadPosts();
  },

  loadPosts() {
    let that = this;
    let uid = wx.getStorageSync('uid');
    this.setData({
      uid:uid
    })
    // if (!uid) wx.switchTab({
    //   url: '/pages/me/me',
    // });
    console.log("*******");
    wx.request({
      url:'http://127.0.0.1:3527/posts/findall/'+wx.getStorageSync('uid'),
      method:'GET',
      success(res){
        const result = res.data.data;
        let list = that.data.postsList;
        const processedList = res.data.data.map(item => {
          return {
            ...item, // 保留原始字段
            formatTime: formatTime(item.post_time) // 添加格式化时间字段
          };
        });
        that.setData({
          postsList:processedList
        })
      }
    })
  },

  // 搜索输入处理
  onSearchInput(e) {
    this.setData({
      searchText : e.detail.trim()
    })
    console.log(this.data.searchText);
  },

  onSearch(){
    console.log("@#$#@");
    let that = this;
    wx.request({
      url: `http://127.0.0.1:3527/posts/search?user_id=${wx.getStorageSync('uid')}&content=${this.data.searchText}`,
      method:`GET`,
      success(res){
        const result = res.data.data;
        let list = that.data.postsList;
        const processedList = res.data.data.map(item => {
          return {
            ...item, // 保留原始字段
            formatTime: formatTime(item.post_time) // 添加格式化时间字段
          };
        });
        that.setData({
          postsList:processedList
        })
      }
    })
  },

  addLike(id,useful,cancel){
    let that = this;
    const posts = this.data.postsList.map(post => {
      if (post.post_id === id){
        if (useful === 1){
          wx.request({
            url:'http://127.0.0.1:3527/posts/like',
            method:'PUT',
            data:{
              "post_id":id,
              "user_id":wx.getStorageSync('uid'),
              "like":1,
              "dislike":0,
              "act":post.act,
              "cancel":cancel
            },
          });
        } else if (useful === -1){
          wx.request({
            url:'http://127.0.0.1:3527/posts/like',
            method:'PUT',
            data:{
              "post_id":id,
              "user_id":wx.getStorageSync('uid'),
              "like":0,
              "dislike":1,
              "act":post.act,
              "cancel":cancel
            },
          })
        } else{
          wx.request({
            url:'http://127.0.0.1:3527/posts/like',
            method:'PUT',
            data:{
              "post_id":id,
              "user_id":wx.getStorageSync('uid'),
              "like":0,
              "dislike":0,
              "act":post.act,
              "cancel":cancel
            },
          });
        };
        post.act = 1;
      }
    })
  },
  // 点赞处理
  likePost(e) {
    const post_id = e.currentTarget.dataset.postid;
    const posts = this.data.postsList.map(post => {
      if (post.post_id === post_id) {
        if (post.liked){
          this.addLike(post_id,0,true);
        } else{
          this.addLike(post_id,1,false);
        }
        return {
          ...post,
          liked: !post.liked,
          like_count: post.like_count + (post.liked ? -1 : 1),
          disliked: false
        }
      }
      return post;
    })
    this.setData({ postsList: posts })
  },

  dislikePost(e) {
    const post_id = e.currentTarget.dataset.postid;
    const posts = this.data.postsList.map(post => {
      if (post.post_id === post_id) {
        if (post.disliked){
          this.addLike(post_id,0,false);
          console.log("*******************");
        } else{
          this.addLike(post_id,-1,post.liked);
        }
        return {
          ...post,
          disliked: !post.disliked,
          like_count: post.like_count + (post.liked ? -1 : 0),
          liked:false,
        }
      }
      return post
    })
    this.setData({ postsList: posts })
  },

   // 点击评论按钮
   toComments(e) {
    let postId = e.currentTarget.dataset.post_id;
    let nickname = e.currentTarget.dataset.nickname; 
    let content = e.currentTarget.dataset.content
    this.setData({
      showCommentPopup: true,
      currentPostId: postId,  // 动态更新当前帖子ID
      currentNickname:nickname,
      currentContent:content
    });
  },

  onInputChange(e){
    this.setData({
      content: e.detail.value
    });
  },

  submitComment(e){
    console.log(this.data.content);
    let that = this;
    let pid = this.data.currentPostId;
    let text = this.data.content;
    wx.request({
      url:'http://127.0.0.1:3527/reviews/add',
      method:'POST',
      data:{
        "user_id":wx.getStorageSync('uid'),
        "post_id":pid,
        "review": text 
      },
      success(res){
        console.log("FFFFFFFFFFFFFFFFFFFFFFFFFF");
        const posts = that.data.postsList.map(post => {
          if (post.post_id === pid) {
            return {
              ...post,
              review_count: post.review_count + 1,
            }
          }
          return post;
        });
        that.setData({
          postsList: posts,
          showCommentPopup: false,
          currentPostId: null,  // 记录当前操作的帖子ID
          currentContent:null,
          postId:null,
          currentNickname:null,
          content:null,
        });
      }
    })
  },

  // 关闭弹窗
  closeCom() {
    this.setData({     
      showCommentPopup: false,
      currentPostId: null,  // 记录当前操作的帖子ID
      currentContent:null,
      postId:null,
      currentNickname:null,
      content:null
    });
  },

  // 跳转详情页
  toPostDetail(e) {
    let postId = e.currentTarget.dataset.postid;
    let uid = wx.getStorageSync('uid');
    wx.navigateTo({
      url: `/pages/detail/detail?pid=${postId}&uid=${uid}`,
      success: (res) => console.log('跳转成功',res),
      fail: (err) => console.error('跳转失败', err)
    })
  },

  // 跳转发帖页
  toCreatePost() {
    wx.navigateTo({
      url: '/pages/createPost/createPost'
    })
  },

  onPullDownRefresh() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
    setTimeout(() => {
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      wx.stopPullDownRefresh(); // 必须调用，否则页面会保持下拉状态
    }, 1000);
  }
})